package com.open.cloud.rabbitmq.config;

import com.open.cloud.rabbitmq.producer.FastBuildRabbitMqProducer;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自动配置
 * @author kong
 * @date 2021/4/6
 * blog: http://blog.kongyin.ltd
 */
@Configuration
@ConditionalOnClass(FastBuildRabbitMqProducer.class)
@EnableConfigurationProperties(RabbitMQProperties.class)
public class RabbitMQAutoConfigure {

    @Autowired
    private RabbitMQProperties rabbitMQProperties;

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        return new RabbitTemplate(connectionFactory);
    }

    @Bean
    @ConditionalOnMissingBean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setAddresses(rabbitMQProperties.getAddresses());
        cachingConnectionFactory.setUsername(rabbitMQProperties.getUsername());
        cachingConnectionFactory.setPassword(rabbitMQProperties.getPassword());
        cachingConnectionFactory.setVirtualHost(rabbitMQProperties.getVirtualHost());
        cachingConnectionFactory.setPublisherConfirms(rabbitMQProperties.isPublisherConfirms());
        return cachingConnectionFactory;
    }


    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "opc-frame.rabbitmq", value = "enable", havingValue = "true")
    public FastBuildRabbitMqProducer fastBuildRabbitMqProducer(ConnectionFactory connectionFactory){
        return new FastBuildRabbitMqProducer(connectionFactory);
    }
}
